import Dingo.API as api
import random
#import debug    
Colors = api.SensorColor

__author__ = "John Kemp"
_debug = False

# Fixed position nodes are assumed to be listeners
nodes = [(50, 50), (150, 150, "Actuator"), (200, 200)]
colours = {"Actuator":Colors.Red, "Listener":Colors.Green}

class TheSimulation(api.Simulation):
    def __init__(self, graph):
        if _debug: debug.writeHeader()
        ether = api.Ether(self)
	api.Ether.RF_radius = 400
        sensors = (ASensor(graph, ether, i) for i in xrange(len(nodes)))
        api.Simulation.__init__(self, sensors, graph)

    def run(self):
        super(TheSimulation, self).run()


class APacket(api.Packet):
	def __init__(self, sender, data):
		api.Packet.__init__(self, sender, None, data)
		return


class ASensor(api.Sensor):
    def __init__(self, graph, ether, i):
        x, y = nodes[i][:2]
        if len(nodes[i]) == 2:
            self.state = "Listener"
        else:
            self.state = "Actuator"
        self.colour = colours[self.state]

        # --- Start editing ---

        #  --- Stop editing ---

        sched = api.Scheduler([ATask(self)], -1)
        api.Sensor.__init__(self, graph, "Sensor[%d]" % i, (x, y), self.colour, sched, ether)
        if _debug: debug.writeInfo(self, x, y)


class ATask(api.Task):  
    def __init__(self, sensor):
        sensor.tick = 0                 # Useful for keeping track of cycles
        api.Task.__init__(self, 0, 0, sensor)
    
    def task(self):
        node = self.sensor.node
        sensor = self.sensor
        sensor.tick += 1

        # --- Start editing ---
        if sensor.state == "Actuator":
            if sensor.tick % 10 == 9:
                packet = APacket(sensor.id, 0)
                sensor.broadcast(api.SensorColor.FromName("Blue"), None, packet)
        elif sensor.state == "Listener":
            if not sensor.recv_q.empty():
                packet = sensor.recv_q.get()
                print sensor.id + " - " + packet.__repr__()
        # --- Stop editing ---

        api.Sleep(0.2)                  # Give the UI a chance
